package com.hw.pusher;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.huawei.agconnect.config.AGConnectServicesConfig;
import com.huawei.hms.aaid.HmsInstanceId;
import com.hw.pusher.push.PushData;
import com.hw.pusher.stream.FlutterEventChannel;
import com.hw.pusher.utils.DeviceUtils;
import com.hw.pusher.utils.Logger;

import java.util.Random;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;

public class HWPushActivity extends FlutterActivity {
    /**
     * _data key的值需要参考，PushData格式
     */
    public static final String _data = "_data";
    public static final String _type = "_type";
    public static final String BRAND_MI = "XIAOMI";
    public static final String BRAND_HUAWEI = "HUAWEI";
    public static final int _what = 0x0010000;
    private static FlutterEventChannel flutterEventChannel;

    public static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == _what && null != flutterEventChannel) {
                if (!flutterEventChannel.registered()) {
                    Message message = Message.obtain(msg);
                    postDelayed(()-> sendMessage(message), 300);
                }else  {
                    PushData pushData = (PushData) msg.obj;
                    Logger.d("handleMessage ------>"+pushData.toJson());
                    if (flutterEventChannel.registered()) {
                        flutterEventChannel.sendEvent(pushData.toJson());
                        Logger.d("handleMessage ------>registered is true");
                    }
                    else {
                        Logger.d("handleMessage ------>registered is false");
                    }
                }
            }
        }
    };

    void sentEvent(String message) {
        if (null != flutterEventChannel && flutterEventChannel.registered()) {
            flutterEventChannel.sendEvent(message);
        }
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterEventChannel = FlutterEventChannel.create(flutterEngine);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntentByType(getIntent());
        if (BRAND_HUAWEI.equals(DeviceUtils.getDeviceBrand())) getToken();
    }

    @Override
    protected void onNewIntent(@NonNull Intent intent) {
        super.onNewIntent(intent);
        handleIntentByType(intent);
    }

    //获取token
    private void getToken() {
        Logger.d("get huawei token: begin");
        new Thread() {
            @Override
            public void run() {
                try {
                    String appId = AGConnectServicesConfig.fromContext(HWPushActivity.this).getString("client/app_id");
                    String pushToken = HmsInstanceId.getInstance(HWPushActivity.this).getToken(appId, "HCM");
                    if (!TextUtils.isEmpty(pushToken)) {
                        Logger.d("get token:" + pushToken);
                        freshToken(pushToken, BRAND_HUAWEI);
                    }
                } catch (Exception e) {
                    Logger.d("getToken failed, " + e);
                }
            }
        }.start();
    }

    private void handleIntentByType(Intent intent) {
        Logger.d("==============================>getIntentData");
        if (null != intent) {
            String type = intent.getStringExtra(_type);
            if (BRAND_MI.equals(type)) {
                handleXiaoMi(intent);
            } else {
                handleHuawei(intent);
            }
        }
    }

    private void handleXiaoMi(Intent intent) {
        String data = intent.getStringExtra(_data);
        if (!TextUtils.isEmpty(data)) {
            postMessageToFlutter(data);
        }
    }

    private void handleHuawei(Intent intent) {
        // 开发者可以通过如下三行代码获取的值做打点统计
        String data = intent.getStringExtra(_data);
        if (!TextUtils.isEmpty(data)) {
            postMessageToFlutter(getPushData(data, BRAND_HUAWEI).toJson());
        }
    }

    /**
     * 数据格式
     * @param msg  {"action":1,"type":"Xiaomi","token":"","message":"{\"key\":12,\"val\":\"wewrqr\"}"}
     */
    private void postMessageToFlutter(String msg) {
        if (null != flutterEventChannel ) {
            if (flutterEventChannel.registered()) {
                flutterEventChannel.sendEvent(msg);
            }else
                handler.postDelayed(()-> flutterEventChannel.sendEvent(msg), 1*1000);
        }
    }

    private void freshToken(String token, String brand) {
        PushData pushData = new PushData();
        pushData.setType(brand);
        pushData.setToken(token);
        pushData.setAction(0);
        HWPushActivity.handler.postDelayed(() -> HWPushActivity.handler.sendMessage(createMessage(pushData)), 1 * 1000);
    }

    PushData getPushData(String message, String brand) {
        PushData pushData = new PushData();
        pushData.setType(brand);
        pushData.setAction(1);
        pushData.setMessage(message);
        return pushData;
    }

    public static Message createMessage(Object object) {
        Message message = new Message();
        message.what = _what;
        message.obj = object;
        return message;
    }
}
